package com.java.tutorials.spring.BatchSqlUpdate;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.BatchSqlUpdate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;
import java.sql.Types;

/**
 * Created by xuzhike on 2016/2/1.
 * http://www.java2s.com/Code/Java/Spring/UseBatchSqlUpdateToInsert5000Rows.htm
 * Use BatchSqlUpdate To Insert 5000 Rows
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:Spring-database.xml"})
public class BatchSqlUpdateTest {
    @Autowired
    public ApplicationContext ctx;
    @Test
    public void test(){
        DataSource dataSource = (DataSource) ctx.getBean("dataSource");
        // DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");

        BatchInsert batchInsert = new BatchInsert(dataSource);
        int count = 5000;
        for (int i = 0; i < count; i++) {
            batchInsert.update(new Object[] { i + 100L, "a" + i, "b" + i, null });
        }
    }
}

class BatchInsert extends BatchSqlUpdate {
    private static final String SQL = "insert into t_customer (id, first_name, last_name, last_login, "
            + "comments) values (?, ?, ?, ?, null)";

    BatchInsert(DataSource dataSource) {
        super(dataSource, SQL);
        declareParameter(new SqlParameter(Types.INTEGER));
        declareParameter(new SqlParameter(Types.VARCHAR));
        declareParameter(new SqlParameter(Types.VARCHAR));
        declareParameter(new SqlParameter(Types.TIMESTAMP));

        setBatchSize(10);
    }

}
